const express = require("express")
const router = express.Router()
const jwt = require("jsonwebtoken")
const journalDB = require("../../db/journal")
const adminDB = require("../../db/admin")

// 密钥
const cort = "coderxinxin2022-04-15"

// 存入日志信息
router.post("/store", async (req, res) => {
  try {
    // 日志标题  日志类型
    const { type } = req.body

    // 登录日志
    if (type == 0) {
      // 登录用户名  登录设备  IP地址  位置信息
      const { author, equipment, loginIP, loginPosition } = req.body
      await journalDB.create({
        type,
        author,
        equipment,
        loginIP,
        loginPosition,
      })
    }
    // 错误日志
    else if (type == 1) {
      // 操作类型
      const { author, operationType } = req.body
      await journalDB.create({
        type,
        author,
        operationType,
      })
    }
    // 操作日志
    else if (type == 2) {
    }

    res.send({
      code: 0,
      mes: "日志添加成功",
    })
  } catch (error) {
    console.log(error)
    res.send({
      code: 5,
      mes: "服务器异常,请稍后再试",
    })
  }
})

// 身份校验 检验是否为超管
router.use(async (req, res, next) => {
  try {
    // 校验token
    // 获取请求头里面的token
    let token = (req.headers.authorization || "").slice(7)
    let info = null
    // 捕获错误
    try {
      info = jwt.verify(token, cort)
      const doc = await adminDB.findById(info._id)
      // 检测超管身份
      if (!doc.supertube)
        return res.send({
          code: 4,
          mes: "您不具有该权限",
        })
      if (!doc)
        return res.send({
          code: 4,
          mes: "系统检测到该账号已被注销",
        })
      // 检测密码是否更新
      if (info.pass !== doc.pass)
        return res.send({
          code: 4,
          mes: "密码已更新,请重新登录",
        })
      next()
    } catch (error) {
      return res.send({
        code: 4,
        mes: "登录信息已过期,请重新登录",
      })
    }
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试",
    })
  }
})

// 请求日志信息 0 => 登录日志，1 => 报错日志，2 => 操作日志
router.get("/requset", async (req, res) => {
  try {
    const { type, skip, limit } = req.query
    // 日志列表
    let journalList = []
    // 某一分类下的日志数量
    let allNums = 0
    // 登录日志
    if (type == 0) {
      journalList = await journalDB
        .find(
          { type: type * 1 },
          {},
          {
            skip: skip * 1,
            limit: limit * 1,
            sort: { time: -1 },
          }
        )
        .populate("author", { name: 1, avatar: 1 })
      // 获取该分类所有的日志数
      allNums = await (await journalDB.find({ type: type * 1 })).length
    }
    // 报错日志
    else if (type == 1) {
    }
    // 操作日志
    else if (type == 2) {
      journalList = await journalDB
        .find(
          { type: type * 1 },
          { operationType: 1, time: 1 },
          {
            skip: skip * 1,
            limit: limit * 1,
            sort: { time: -1 },
          }
        )
        .populate("author", { name: 1, avatar: 1 })
      // 获取该分类所有的日志数
      allNums = await (await journalDB.find({ type: type * 1 })).length
    }
    res.send({
      code: 0,
      mes: "日志数据",
      data: {
        journalList,
        allNums,
      },
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常,请稍后再试",
    })
  }
})

// 搜索登录日志信息列表
router.post("/searchlogin", async (req, res) => {
  try {
    // 用户id 登录时间范围(初始登录时间, 终止登录时间) 设备名称 获取消息的条数, 获取数据起始值
    const { author, startTime, endTime, equipment, limit, skip } = req.body
    // 日志列表
    let journalList = []
    // 当前搜索总数
    let allNums = 0
    // 设备是全部
    if (equipment == 3) {
      // 是否有时间范围选择
      if (!startTime || !startTime) {
        journalList = await journalDB
          .find(
            {
              type: 0,
              author,
            },
            {},
            { sort: { time: -1 }, skip: skip * 1, limit: limit * 1 }
          )
          .populate("author", { name: 1, avatar: 1 })
        allNums = await (
          await journalDB.find(
            {
              type: 0,
              author,
            },
            {},
            { sort: { time: -1 } }
          )
        ).length
      } else {
        journalList = await journalDB.find(
          {
            type: 0,
            author,
            time: {
              $gt: startTime,
              $lt: endTime,
            },
          },
          {},
          { sort: { time: -1 }, limit, skip }
        )
        allNums = await (
          await journalDB.find(
            {
              type: 0,
              author,
              time: {
                $gt: startTime,
                $lt: endTime,
              },
            },
            {},
            { sort: { time: -1 } }
          )
        ).length
      }
    } else {
      // 是否有时间范围选择
      if (!startTime || !startTime) {
        journalList = await journalDB
          .find(
            {
              type: 0,
              author,
              equipment,
            },
            {},
            { sort: { time: -1 }, limit: limit * 1, skip: skip * 1 }
          )
          .populate("author", { name: 1, avatar: 1 })
        allNums = await (
          await journalDB.find(
            {
              type: 0,
              author,
              equipment,
            },
            {},
            { sort: { time: -1 } }
          )
        ).length
      } else {
        journalList = await journalDB
          .find(
            {
              type: 0,
              author,
              equipment,
              time: {
                $gt: startTime,
                $lt: endTime,
              },
            },
            {},
            { sort: { time: -1 }, limit: limit * 1, skip: skip * 1 }
          )
          .populate("author", { name: 1, avatar: 1 })
        allNums = await (
          await journalDB.find(
            {
              type: 0,
              author,
              equipment,
              time: {
                $gt: startTime,
                $lt: endTime,
              },
            },
            {},
            { sort: { time: -1 } }
          )
        ).length
      }
    }
    res.send({
      code: 0,
      mes: "搜索日志列表信息",
      data: {
        journalList,
        allNums,
      },
    })
  } catch (error) {
    console.log(error)
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试",
    })
  }
})

// 搜索操作日志信息列表
router.post("/searchOperation", async (req, res) => {
  try {
    /**
     * startTime: 操作起始时间
     * endTime: 操作终止时间
     * operationType: 操作类型 0 => 用户更新了个人资料  1 => 用户修改密码  2 => 用户修改头像 3 => 用户修改封面
     * limit: 请求数据数量
     * skip: 请求数据初始值
     */
    const { startTime, endTime, operationType, limit, skip } = req.body
    // 日志列表
    let journalList = []
    // 当前搜索总数
    let allNums = 0
    // 设备是全部
    if (operationType == 4) {
      journalList = await journalDB
        .find(
          { type: 2 },
          { operationType: 1, time: 1 },
          {
            limit: limit * 1,
            skip: skip * 1,
            sort: { time: -1 },
          }
        )
        .populate("author", { name: 1, avatar: 1 })
      allNums = await (
        await journalDB.find({ type: 2 }, { operationType: 1, time: 1 })
      ).length
    } else {
      // 判断是否有选择时间
      if (!startTime || !endTime) {
        // 不含时间
        journalList = await journalDB
          .find(
            {
              operationType,
              type: 2,
            },
            { operationType: 1, time: 1 },
            {
              limit: limit * 1,
              skip: skip * 1,
              sort: { time: -1 },
            }
          )
          .populate("author", { name: 1, avatar: 1 })
        allNums = await (
          await journalDB.find(
            {
              operationType,
              type: 2,
            },
            { operationType: 1, time: 1 }
          )
        ).length
      } else {
        journalList = await journalDB
          .find(
            {
              operationType,
              time: {
                $gt: startTime,
                $lt: endTime,
              },
            },
            { operationType: 1, time: 1 },
            {
              limit: limit * 1,
              skip: skip * 1,
              sort: { time: -1 },
            }
          )
          .populate("author", { name: 1, avatar: 1 })
        allNums = await (
          await journalDB.find(
            {
              operationType,
              time: {
                $gt: startTime,
                $lt: endTime,
              },
            },
            { operationType: 1, time: 1 }
          )
        ).length
      }
    }

    res.send({
      code: 0,
      mes: "搜索操作日志列表",
      data: {
        journalList,
        allNums,
      },
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试",
    })
  }
})

// 删除日志
router.post("/delete", async (req, res) => {
  try {
    const { journalID } = req.body
    // 查询该日志是否存在
    const doc = await journalDB.findById(journalID)
    if (!doc)
      return res.send({
        code: 3,
        mes: "该日志已被删除",
      })
    // 删除
    await journalDB.findByIdAndRemove(journalID)
    res.send({
      code: 0,
      mes: "该日志删除成功",
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常,请稍后再试",
    })
  }
})
module.exports = router
